package com.sui.bigdata.sml.web.misc.websocket;

import com.feidee.fdcommon.util.ToolUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author songhaicheng
 * @Date 2019/8/1 15:21
 * @Description
 * @Reviewer
 */
@ServerEndpoint(value = "/web/ws/log/{nid}")
@Component
@Slf4j
public class NodeLogServer {
    private Session session;
    private String nid;

    /**
     * 保存每个客户端的 WebSocket 连接对象
     */
    private static CopyOnWriteArraySet<NodeLogClient> clients = new CopyOnWriteArraySet<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("nid") String nid) {
        this.nid = nid;
        this.session = session;
        NodeLogClient client = new NodeLogClient(nid, session);
        clients.add(client);
        log.debug("{} 开始读取节点【{}】的运行日志", session.getId(), nid);
        client.start();
    }

    @OnClose
    public void onClose() {
        clients.forEach(client -> {
            if (client.getSession() == session) {
                // 停止监听日志内容
                client.stopPushingLog();
                clients.remove(client);
            }
        });
        log.debug("{} 结束对节点【{}】运行日志的读取", session.getId(), nid);
    }

    @OnMessage
    public void onMessage(String message) {
        log.debug("节点 {} 收到日志内容：{}", nid, message);
    }

    @OnError
    public void onError(Throwable e) {
        log.error(session.getId() + " 读取节点【" + nid + "】日志出错", e);
    }

    public void sendMessageToAll(String message) {
        log.debug("【读取日志】发送全局消息：{}", message);
        clients.forEach(client -> {
            try {
                client.getSession().getBasicRemote().sendText(message);
            } catch (IOException e) {
                log.error("【读取日志】全局消息时发生错误，连接 id " + client.getSession().getId(), e);
            }
        });
    }

    public synchronized static void sendMessage(String message, String nid) {
        if (!ToolUtils.isNotNull(nid)) {
            throw new RuntimeException("节点 id 不能为空");
        }
        clients.forEach(client -> {
            if (client.getNid().equals(nid)) {
                try {
                    client.getSession().getBasicRemote().sendText(message);
                } catch (IOException e) {
                    log.error("发送运行日志给连接 id " + client.getSession().getId() + " 时发生错误", e);
                }
            }
        });
    }

    public static void closeClient(String nid) {
        log.debug("【读取日志】关闭对节点 {} 的 websocket 连接", nid);
        clients.forEach(client -> {
            if (client.getNid().equals(nid)) {
                try {
                    client.getSession().close();
                    clients.remove(client);
                } catch (IOException e) {
                    log.error("关闭对节点 " + nid + " 的运行日志读取失败", e);
                }
            }
        });
    }

    public static void closeAllClients() {
        log.debug("【读取日志】关闭所有本机 websocket 连接");
        clients.forEach(client -> {
            try {
                client.getSession().close();
                clients.remove(client);
            } catch (IOException e) {
                log.error("全局关闭运行日志读取连接时发生错误，连接 id" + client.getSession().getId(), e);
            }
        });
    }

}